<template>
    <div>
        <!-- 下拉框与新增按钮放在同一行 -->
        <div class="controls">
            <el-select v-model="selectedType" placeholder="请选择标注对象类型" style="flex: 1;">
                <el-option v-for="type in types" :key="type.value" :label="type.label" :value="type.value" />
            </el-select>
            <el-button @click="addNewNode">新增标注对象</el-button>
        </div>

        <!-- 树形结构 -->
        <el-tree ref="treeRef" :data="treeData" node-key="id" :props="defaultProps" @node-click="handleNodeClick">
            <template #default="{ node, data }">
                <span class="custom-tree-node">{{ data.label }}</span>
                <span class="actions">
                    <el-icon>
                        <Delete @click.stop="deleteNode(data)" />
                    </el-icon>
                    <el-icon>
                        <View @click.stop="toggleVisibility(data)" />
                    </el-icon>
                    <!-- 新增子节点按钮仅在根节点显示 -->
                    <span v-if="hasChildren(data)">
                            <el-icon>
                                <CirclePlus @click.stop="addChildNode(node)" />
                            </el-icon>
                    </span>
                </span>
            </template>
        </el-tree>
    </div>
</template>

<script>
export default {
    data() {
        return {
            selectedType: '',
            types: [
                { value: 'type1', label: '类型1' },
                { value: 'type2', label: '类型2' },
                { value: 'type3', label: '类型3' }
            ],
            treeData: [
                {
                    id: 1,
                    label: 'Parent 1',
                    children: [
                        { id: 2, label: 'Child 1-1' },
                        { id: 3, label: 'Child 1-2' }
                    ]
                },
                {
                    id: 4,
                    label: 'Parent 2',
                    children: [
                        { id: 5, label: 'Child 2-1' }
                    ]
                }
            ],
            defaultProps: {
                children: 'children',
                label: 'label'
            }
        };
    },
    methods: {
        hasChildren(data) {
            // 这里可以直接检查 data 是否有 children 属性以及 children 是否非空
            console.log('我是', Object.keys(data).includes('children'));

            return Object.keys(data).includes('children')
        },
        handleNodeClick(data) {
            console.log('Clicked node:', data);
        },
        addNewNode() {
            if (this.selectedType) {
                const newNode = {
                    id: this.treeData.length + 1,
                    label: `ten${this.treeData.length + 1}`,
                    children: [],
                    type: this.selectedType
                };
                this.treeData.push(newNode);
                this.selectedType = ''; // 清空下拉框选择
            }
            console.log('this.treeData', this.treeData);
        },
        deleteNode(data) {
            const parent = this.findParent(data);
            if (parent && parent.children) {
                const index = parent.children.findIndex(child => child.id === data.id);
                if (index !== -1) {
                    parent.children.splice(index, 1);
                    console.log(`Deleted node with ID ${data.id}`);
                } else {
                    console.error(`Node with ID ${data.id} not found in parent's children.`);
                }
            } else {
                console.error('Parent or parent.children is undefined.');
            }
        },
        toggleVisibility(data) {
            // Implement visibility toggle logic here
            console.log('Toggle visibility for:', data);
        },
        findParent(data) {
            let parent = null;
            const findParentRecursive = (nodes) => {
                if (!nodes || !nodes.length) return;
                nodes.forEach(node => {
                    if (node.children && node.children.some(child => child.id === data.id)) {
                        parent = node;
                        return;
                    }
                    findParentRecursive(node.children);
                });
            };
            findParentRecursive(this.treeData);
            return parent;
        },
        addChildNode(node) {
            // 确保即使没有 children 属性也创建一个空数组
            // if (!node.data.children) {
            //     node.data.children = [];
            // }
            const newNode = {
                id: this.generateUniqueID(), // 确保新节点的 ID 是唯一的
                label: `Child ${node.data.children.length + 1}`,
                // children: []
            };
            node.data.children.push(newNode);
        },
        generateUniqueID() {
            // 简单的唯一 ID 生成器
            return Math.max(...this.getAllIDs(), 0) + 1;
        },
        getAllIDs() {
            // 获取所有节点的 ID
            const ids = [];
            const collectIDs = (nodes) => {
                if (!nodes || !nodes.length) return;
                nodes.forEach(node => {
                    ids.push(node.id);
                    collectIDs(node.children);
                });
            };
            collectIDs(this.treeData);
            return ids;
        }
    }
};
</script>

<style scoped>
.controls {
    display: flex;
    align-items: center;
    /* 垂直居中 */
    gap: 8px;
    /* 组件之间的间距 */
}

.custom-tree-node {
    flex: 1;
    padding-right: 8px;
}

.actions {
    display: flex;
    gap: 8px;
}

.add-text {
    margin-left: 8px;
    cursor: pointer;
    color: #409eff;
    font-size: 14px;
}
</style>